package com.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Random;

/**
 * Author Name: Justice
 * Project Name: zookeepercurator
 * File Name: Barrier1
 * Package Name: com.curator
 * Date: 2020-02-22 22:53
 * Copyright (c) 2020,All Rights Reserved.
 * 类似于王者荣耀,必须n个人都准备好了才执行,必须等所有人都结束了才结束
 */


public class Barrier1 {
    public static void main(String[] args) throws Exception {
        // 超时后等1秒再重试, 最多重试5次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        final CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(AddressUtil.ADDRESS)
                .connectionTimeoutMs(10000).sessionTimeoutMs(10000)
                .retryPolicy(retryPolicy)
                .build();
        // 开启
        curatorFramework.start();
        for (int i = 0; i < 5; i++) {
            new Thread("线程" + i) {
                @Override
                public void run() {
                    // 5代表5个客户端连接后才执行
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(curatorFramework, "/barrer01", 5);
                    try {
                        // 模拟每个玩家加载游戏进度不一致的情况
                        Thread.sleep(new Random().nextInt(5000));
                        System.err.println(Thread.currentThread().getName() + "准备好了");
                        // 等待进入游戏
                        barrier.enter();
                        System.err.println("大家都开始了");
                        // 模拟游戏的进度
                        Thread.sleep(new Random().nextInt(5000));
                        // 模拟游戏的进度
                        barrier.leave();
                        System.err.println(Thread.currentThread().getName() + "退出完成");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}
